package com.whj.servicemap.remote;

import com.whj.internalcommon.constant.AMapConfigConstant;
import com.whj.internalcommon.dto.ResponseResult;
import com.whj.internalcommon.request.PointsDTO;
import com.whj.internalcommon.request.PointsRequestDTO;
import com.whj.internalcommon.response.TrackResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

/**
 * @Auther: wanghaijun
 * @Date: 2023/1/20 - 01 - 20 - 13:05 
 * @Description: com.whj.servicemap.remote
 */

@Service
@Slf4j
public class PointClient {
    @Value("${amap.key}")
    private String amapKey;

    @Value("${amap.sid}")
    private String amapSid;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 上传位置信息 调用高德api
     * @param pointRequest
     * @return
     */
    public ResponseResult<TrackResponse> upload(PointsRequestDTO pointRequest) {

        // &key=<用户的key>
        // 拼装请求的url
        StringBuilder url = new StringBuilder();
        url.append(AMapConfigConstant.POINT_UPLOAD_URL);
        url.append("?");
        url.append("key="+amapKey);
        url.append("&");
        url.append("sid="+amapSid);
        url.append("&");
        url.append("tid="+pointRequest.getTid());
        url.append("&");
        url.append("trid="+pointRequest.getTrid());
        url.append("&");
        url.append("points=");
        PointsDTO[] points = pointRequest.getPoints();
        url.append("%5B");
        for (PointsDTO p : points
        ) {
            url.append("%7B");
            String locatetime = p.getLocatetime();
            String location = p.getLocation();
            url.append("%22location%22");
            url.append("%3A");
            url.append("%22"+location+"%22");
            url.append("%2C");

            url.append("%22locatetime%22");
            url.append("%3A");
            url.append(locatetime);

            url.append("%7D");
        }
        url.append("%5D");

        log.info("上传位置请求："+url.toString());
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(URI.create(url.toString()), null, String.class);
        log.info("上传位置响应："+stringResponseEntity.getBody());
        return ResponseResult.success("");
    }
}
